#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
using namespace std;
#define NUM 1024
void *reads(void *args)
{
    // 线程分离
    pthread_detach(pthread_self());
    char buffer[NUM];
    // 清空buffer
    memset(buffer, 0, NUM);
    int *sc = static_cast<int *>(args);
    sockaddr_in reader;
    socklen_t len = sizeof(reader);
    while (true)
    {
        ssize_t s = recvfrom(*sc, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&reader, &len);
        if (s > 0)
        {
            cout << buffer << endl;
            memset(buffer, 0, NUM);
        }
        else
            break;
    }
    return nullptr;
}
int main(int argc, char *argv[])
{
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cout << "sock enrro" << endl;
        exit(1);
    }

    char buffer[NUM];
    memset(buffer, 0, NUM);
    pthread_t tid;
    pthread_create(&tid, nullptr, reads, &sock);

    sockaddr_in clinet;
    memset(&clinet, 0, sizeof(clinet));
    clinet.sin_family = AF_INET;
    clinet.sin_addr.s_addr = inet_addr(argv[1]);
    clinet.sin_port = htons(atoi(argv[2]));
    while (true)
    {
        cout << "你要输入" << endl;
        cin >> buffer;
        ssize_t s = sendto(sock, buffer, sizeof(buffer), 0, (sockaddr *)&(clinet), sizeof(clinet));
        if (s > 0)
            memset(buffer, 0, NUM);
        else
            break;
    }
    close(sock);
    return 0;
}